<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT">










<meta name="description" content="什么是跨域？跨域是指一个域下的文档或脚本试图去请求另一个域下的资源，这里跨域是广义的。 广义的跨域：1231.) 资源跳转： A链接、重定向、表单提交2.) 资源嵌入： &amp;lt;link&amp;gt;、&amp;lt;script&amp;gt;、&amp;lt;img&amp;gt;、&amp;lt;frame&amp;gt;等dom标签，还有样式中background:url()、@font-face()等文件外链3.) 脚本请求： js发起的a">
<meta property="og:type" content="article">
<meta property="og:title" content="跨域">
<meta property="og:url" content="http://blog.xiaowuzi.info/2016/05/07/跨域/index.html">
<meta property="og:site_name" content="小武子博客">
<meta property="og:description" content="什么是跨域？跨域是指一个域下的文档或脚本试图去请求另一个域下的资源，这里跨域是广义的。 广义的跨域：1231.) 资源跳转： A链接、重定向、表单提交2.) 资源嵌入： &amp;lt;link&amp;gt;、&amp;lt;script&amp;gt;、&amp;lt;img&amp;gt;、&amp;lt;frame&amp;gt;等dom标签，还有样式中background:url()、@font-face()等文件外链3.) 脚本请求： js发起的a">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-04-17T12:23:07.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="跨域">
<meta name="twitter:description" content="什么是跨域？跨域是指一个域下的文档或脚本试图去请求另一个域下的资源，这里跨域是广义的。 广义的跨域：1231.) 资源跳转： A链接、重定向、表单提交2.) 资源嵌入： &amp;lt;link&amp;gt;、&amp;lt;script&amp;gt;、&amp;lt;img&amp;gt;、&amp;lt;frame&amp;gt;等dom标签，还有样式中background:url()、@font-face()等文件外链3.) 脚本请求： js发起的a">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.xiaowuzi.info/2016/05/07/跨域/">





  <title>跨域 | 小武子博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">小武子博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.xiaowuzi.info/2016/05/07/跨域/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tony">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="小武子博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">跨域</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-05-07T22:46:18+08:00">
                2016-05-07
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/javascript基础/" itemprop="url" rel="index">
                    <span itemprop="name">javascript基础</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="什么是跨域？"><a href="#什么是跨域？" class="headerlink" title="什么是跨域？"></a>什么是跨域？</h3><p>跨域是指一个域下的文档或脚本试图去请求另一个域下的资源，这里跨域是广义的。</p>
<h4 id="广义的跨域："><a href="#广义的跨域：" class="headerlink" title="广义的跨域："></a>广义的跨域：</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">1.) 资源跳转： A链接、重定向、表单提交</span><br><span class="line">2.) 资源嵌入： &lt;link&gt;、&lt;script&gt;、&lt;img&gt;、&lt;frame&gt;等dom标签，还有样式中background:url()、@font-face()等文件外链</span><br><span class="line">3.) 脚本请求： js发起的ajax请求、dom和js对象的跨域操作等</span><br></pre></td></tr></table></figure>
<p>其实我们通常所说的跨域是狭义的，是由浏览器同源策略限制的类请求场景。</p>
<h4 id="什么是同源策略？"><a href="#什么是同源策略？" class="headerlink" title="什么是同源策略？"></a>什么是同源策略？</h4><p>同源策略/SOP（Same origin policy）是一种约定，由Netscape公司1995年引入浏览器，它是浏览器最核心也最基本的安全功能，如果缺少了同源策略，浏览器很容易受到XSS、CSFR等攻击。所谓同源是指”协议+域名+端口”三者相同，即便两个不同的域名指向同一个ip地址，也非同源。</p>
<p>同源策略限制以下几种行为：</p>
<blockquote>
<p>1.) Cookie、LocalStorage 和 IndexDB 无法读取</p>
<p>2.) DOM 和 Js对象无法获得</p>
<p>3.) AJAX 请求不能发送</p>
</blockquote>
<h4 id="常见跨域场景"><a href="#常见跨域场景" class="headerlink" title="常见跨域场景"></a>常见跨域场景</h4><a id="more"></a>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">URL                                      说明                    是否允许通信</span><br><span class="line">http://www.domain.com/a.js</span><br><span class="line">http://www.domain.com/b.js         同一域名，不同文件或路径           允许</span><br><span class="line">http://www.domain.com/lab/c.js</span><br><span class="line"></span><br><span class="line">http://www.domain.com:8000/a.js</span><br><span class="line">http://www.domain.com/b.js         同一域名，不同端口                不允许</span><br><span class="line"> </span><br><span class="line">http://www.domain.com/a.js</span><br><span class="line">https://www.domain.com/b.js        同一域名，不同协议                不允许</span><br><span class="line"> </span><br><span class="line">http://www.domain.com/a.js</span><br><span class="line">http://192.168.4.12/b.js           域名和域名对应相同ip              不允许</span><br><span class="line"> </span><br><span class="line">http://www.domain.com/a.js</span><br><span class="line">http://x.domain.com/b.js           主域相同，子域不同                不允许</span><br><span class="line">http://domain.com/c.js</span><br><span class="line"> </span><br><span class="line">http://www.domain1.com/a.js</span><br><span class="line">http://www.domain2.com/b.js        不同域名                         不允许</span><br></pre></td></tr></table></figure>
<h4 id="跨域解决方案"><a href="#跨域解决方案" class="headerlink" title="跨域解决方案"></a>跨域解决方案</h4><ul>
<li>通过jsonp跨域</li>
<li>document.domain + iframe跨域</li>
<li>location.hash + iframe跨域</li>
<li>window.name + iframe跨域</li>
<li>postMessage跨域</li>
<li>跨域资源共享（CORS）</li>
<li>nginx代理跨域</li>
<li>nodejs中间件代理跨域</li>
<li>WebSocket协议跨域</li>
</ul>
<h4 id="一、通过jsonp跨域"><a href="#一、通过jsonp跨域" class="headerlink" title="一、通过jsonp跨域"></a>一、通过jsonp跨域</h4><p>通常为了减轻web服务器的负载，我们把js、css、img等表态资源分离到另一台独立域名的服务器上，在html页面中再通过相应的标签从不同域名下加载静态资源，而被浏览器允许，基于原理，我们可以通过动态创建script，再请求一个带参网址实现跨域通信。</p>
<p>1、原生实现：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">   var script = document.createElement(&apos;script&apos;);</span><br><span class="line">   script.type = &apos;text/javascript&apos;;</span><br><span class="line"></span><br><span class="line">   // 传参并指定回调执行函数为onBack</span><br><span class="line">   script.src = &apos;http://www.domain2.com:8080/login?user=admin&amp;callback=onBack&apos;;</span><br><span class="line">   document.head.appendChild(script);</span><br><span class="line"></span><br><span class="line">   // 回调执行函数</span><br><span class="line">   function onBack(res) &#123;</span><br><span class="line">       alert(JSON.stringify(res));</span><br><span class="line">   &#125;</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>
<p>服务端返回如下（返回时即执行全局函数）：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">onBack(&#123;&quot;status&quot;: true, &quot;user&quot;: &quot;admin&quot;&#125;)</span><br></pre></td></tr></table></figure>
<p>2、jquery ajax:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">$.ajax(&#123;</span><br><span class="line">    url: &apos;http://www.domain2.com:8080/login&apos;,</span><br><span class="line">    type: &apos;get&apos;,</span><br><span class="line">    dataType: &apos;jsonp&apos;,  // 请求方式为jsonp</span><br><span class="line">    jsonpCallback: &quot;onBack&quot;,    // 自定义回调函数名</span><br><span class="line">    data: &#123;&#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>后端node.js代码示例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">var querystring = require(&apos;querystring&apos;);</span><br><span class="line">var http = require(&apos;http&apos;);</span><br><span class="line">var server = http.createServer();</span><br><span class="line"></span><br><span class="line">server.on(&apos;request&apos;, function(req, res) &#123;</span><br><span class="line">    var params = qs.parse(req.url.split(&apos;?&apos;)[1]);</span><br><span class="line">    var fn = params.callback;</span><br><span class="line"></span><br><span class="line">    // jsonp返回设置</span><br><span class="line">    res.writeHead(200, &#123; &apos;Content-Type&apos;: &apos;text/javascript&apos; &#125;);</span><br><span class="line">    res.write(fn + &apos;(&apos; + JSON.stringify(params) + &apos;)&apos;);</span><br><span class="line"></span><br><span class="line">    res.end();</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">server.listen(&apos;8080&apos;);</span><br><span class="line">console.log(&apos;Server is running at port 8080...&apos;);</span><br></pre></td></tr></table></figure>
<p>jsonp缺点：只能实现get一种请求。</p>
<h4 id="二、document-domain-iframe跨域"><a href="#二、document-domain-iframe跨域" class="headerlink" title="二、document.domain+iframe跨域"></a>二、document.domain+iframe跨域</h4><p>此方案仅限主域相同，子域不同的跨域应用场景。</p>
<p>实现原理：两个页面都通过js强制设置document.domain为基础主域，就实现了同域。</p>
<p>1.）父窗口：(<a href="http://www.domain.com/a.html" target="_blank" rel="noopener">http://www.domain.com/a.html</a>)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;iframe id=&quot;iframe&quot; src=&quot;http://child.domain.com/b.html&quot;&gt;&lt;/iframe&gt;</span><br><span class="line">&lt;script&gt;</span><br><span class="line">    document.domain = &apos;domain.com&apos;;</span><br><span class="line">    var user = &apos;admin&apos;;</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>
<p>2.）子窗口：(<a href="http://child.domain.com/b.html" target="_blank" rel="noopener">http://child.domain.com/b.html</a>)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">    document.domain = &apos;domain.com&apos;;</span><br><span class="line">    // 获取父窗口中变量</span><br><span class="line">    alert(&apos;get js data from parent ---&gt; &apos; + window.parent.user);</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>
<h4 id="三、location-hash-iframe跨域"><a href="#三、location-hash-iframe跨域" class="headerlink" title="三、location.hash+iframe跨域"></a>三、location.hash+iframe跨域</h4><p>实现原理： a欲与b跨域相互通信，通过中间页c来实现。 三个页面，不同域之间利用iframe的location.hash传值，相同域之间直接js访问来通信。</p>
<p>具体实现：A域：a.html -&gt; B域：b.html -&gt; A域：c.html，a与b不同域只能通过hash值单向通信，b与c也不同域也只能单向通信，但c与a同域，所以c可通过parent.parent访问a页面所有对象。</p>
<p>1.）a.html：(<a href="http://www.domain1.com/a.html" target="_blank" rel="noopener">http://www.domain1.com/a.html</a>)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">&lt;iframe id=&quot;iframe&quot; src=&quot;http://www.domain2.com/b.html&quot; style=&quot;display:none;&quot;&gt;&lt;/iframe&gt;</span><br><span class="line">&lt;script&gt;</span><br><span class="line">    var iframe = document.getElementById(&apos;iframe&apos;);</span><br><span class="line"></span><br><span class="line">    // 向b.html传hash值</span><br><span class="line">    setTimeout(function() &#123;</span><br><span class="line">        iframe.src = iframe.src + &apos;#user=admin&apos;;</span><br><span class="line">    &#125;, 1000);</span><br><span class="line">    </span><br><span class="line">    // 开放给同域c.html的回调方法</span><br><span class="line">    function onCallback(res) &#123;</span><br><span class="line">        alert(&apos;data from c.html ---&gt; &apos; + res);</span><br><span class="line">    &#125;</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>
<p>2.）b.html：(<a href="http://www.domain2.com/b.html" target="_blank" rel="noopener">http://www.domain2.com/b.html</a>)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&lt;iframe id=&quot;iframe&quot; src=&quot;http://www.domain1.com/c.html&quot; style=&quot;display:none;&quot;&gt;&lt;/iframe&gt;</span><br><span class="line">&lt;script&gt;</span><br><span class="line">    var iframe = document.getElementById(&apos;iframe&apos;);</span><br><span class="line"></span><br><span class="line">    // 监听a.html传来的hash值，再传给c.html</span><br><span class="line">    window.onhashchange = function () &#123;</span><br><span class="line">        iframe.src = iframe.src + location.hash;</span><br><span class="line">    &#125;;</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>
<p>3.）c.html：(<a href="http://www.domain1.com/c.html" target="_blank" rel="noopener">http://www.domain1.com/c.html</a>)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">    // 监听b.html传来的hash值</span><br><span class="line">    window.onhashchange = function () &#123;</span><br><span class="line">        // 再通过操作同域a.html的js回调，将结果传回</span><br><span class="line">        window.parent.parent.onCallback(&apos;hello: &apos; + location.hash.replace(&apos;#user=&apos;, &apos;&apos;));</span><br><span class="line">    &#125;;</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>
<h4 id="四、window-name-iframe跨域"><a href="#四、window-name-iframe跨域" class="headerlink" title="四、window.name + iframe跨域"></a>四、window.name + iframe跨域</h4><p>window.name属性的独特之处：name值在不同的页面（甚至不同域名）加载后依旧存在，并且可以支持非常长的 name 值（2MB）。</p>
<p>1.）a.html：(<a href="http://www.domain1.com/a.html" target="_blank" rel="noopener">http://www.domain1.com/a.html</a>)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">var proxy = function(url, callback) &#123;</span><br><span class="line">    var state = 0;</span><br><span class="line">    var iframe = document.createElement(&apos;iframe&apos;);</span><br><span class="line"></span><br><span class="line">    // 加载跨域页面</span><br><span class="line">    iframe.src = url;</span><br><span class="line"></span><br><span class="line">    // onload事件会触发2次，第1次加载跨域页，并留存数据于window.name</span><br><span class="line">    iframe.onload = function() &#123;</span><br><span class="line">        if (state === 1) &#123;</span><br><span class="line">            // 第2次onload(同域proxy页)成功后，读取同域window.name中数据</span><br><span class="line">            callback(iframe.contentWindow.name);</span><br><span class="line">            destoryFrame();</span><br><span class="line"></span><br><span class="line">        &#125; else if (state === 0) &#123;</span><br><span class="line">            // 第1次onload(跨域页)成功后，切换到同域代理页面</span><br><span class="line">            iframe.contentWindow.location = &apos;http://www.domain1.com/proxy.html&apos;;</span><br><span class="line">            state = 1;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    document.body.appendChild(iframe);</span><br><span class="line"></span><br><span class="line">    // 获取数据以后销毁这个iframe，释放内存；这也保证了安全（不被其他域frame js访问）</span><br><span class="line">    function destoryFrame() &#123;</span><br><span class="line">        iframe.contentWindow.document.write(&apos;&apos;);</span><br><span class="line">        iframe.contentWindow.close();</span><br><span class="line">        document.body.removeChild(iframe);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">// 请求跨域b页面数据</span><br><span class="line">proxy(&apos;http://www.domain2.com/b.html&apos;, function(data)&#123;</span><br><span class="line">    alert(data);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>2.）proxy.html：(<a href="http://www.domain1.com/proxy..." target="_blank" rel="noopener">http://www.domain1.com/proxy...</a>.</p>
<p>中间代理页，与a.html同域，内容为空即可。</p>
<p>3.）b.html：(<a href="http://www.domain2.com/b.html" target="_blank" rel="noopener">http://www.domain2.com/b.html</a>)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">    window.name = &apos;This is domain2 data!&apos;;</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>
<p>总结：通过iframe的src属性由外域转向本地域，跨域数据即由iframe的window.name从外域传递到本地域。这个就巧妙地绕过了浏览器的跨域访问限制，但同时它又是安全操作。</p>
<h4 id="五、postMessage跨域"><a href="#五、postMessage跨域" class="headerlink" title="五、postMessage跨域"></a>五、postMessage跨域</h4><p>postMessage是HTML5 XMLHttpRequest Level 2中的API，且是为数不多可以跨域操作的window属性之一，它可用于解决以下方面的问题：</p>
<ul>
<li>页面和其打开的新窗口的数据传递</li>
<li>多窗口之间消息传递</li>
<li>页面与嵌套的iframe消息传递</li>
<li>上面三个场景的跨域数据传递</li>
</ul>
<p>用法：postMessage(data,origin)方法接受两个参数</p>
<p>data： html5规范支持任意基本类型或可复制的对象，但部分浏览器只支持字符串，所以传参时最好用JSON.stringify()序列化。</p>
<p>origin： 协议+主机+端口号，也可以设置为”*”，表示可以传递给任意窗口，如果要指定和当前窗口同源的话设置为”/“。</p>
<p>1.）a.html：(<a href="http://www.domain1.com/a.html" target="_blank" rel="noopener">http://www.domain1.com/a.html</a>)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">&lt;iframe id=&quot;iframe&quot; src=&quot;http://www.domain2.com/b.html&quot; style=&quot;display:none;&quot;&gt;&lt;/iframe&gt;</span><br><span class="line">&lt;script&gt;       </span><br><span class="line">    var iframe = document.getElementById(&apos;iframe&apos;);</span><br><span class="line">    iframe.onload = function() &#123;</span><br><span class="line">        var data = &#123;</span><br><span class="line">            name: &apos;aym&apos;</span><br><span class="line">        &#125;;</span><br><span class="line">        // 向domain2传送跨域数据</span><br><span class="line">        iframe.contentWindow.postMessage(JSON.stringify(data), &apos;http://www.domain2.com&apos;);</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    // 接受domain2返回数据</span><br><span class="line">    window.addEventListener(&apos;message&apos;, function(e) &#123;</span><br><span class="line">        alert(&apos;data from domain2 ---&gt; &apos; + e.data);</span><br><span class="line">    &#125;, false);</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>
<p>2.）b.html：(<a href="http://www.domain2.com/b.html" target="_blank" rel="noopener">http://www.domain2.com/b.html</a>)</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">    // 接收domain1的数据</span><br><span class="line">    window.addEventListener(&apos;message&apos;, function(e) &#123;</span><br><span class="line">        alert(&apos;data from domain1 ---&gt; &apos; + e.data);</span><br><span class="line"></span><br><span class="line">        var data = JSON.parse(e.data);</span><br><span class="line">        if (data) &#123;</span><br><span class="line">            data.number = 16;</span><br><span class="line"></span><br><span class="line">            // 处理后再发回domain1</span><br><span class="line">            window.parent.postMessage(JSON.stringify(data), &apos;http://www.domain1.com&apos;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;, false);</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>
<h4 id="六、跨域资源共享（CORS）"><a href="#六、跨域资源共享（CORS）" class="headerlink" title="六、跨域资源共享（CORS）"></a>六、跨域资源共享（CORS）</h4><p>普通跨域请求：只服务端设置Access-Control-Allow-Origin即可，前端无须设置，若要带cookie请求：前后端都需要设置。</p>
<p>需注意的是：由于同源策略的限制，所读取的cookie为跨域请求接口所在域的cookie，而非当前页。如果想实现当前页cookie的写入，可参考下文：七、nginx反向代理中设置proxy_cookie_domain 和 八、NodeJs中间件代理中cookieDomainRewrite参数的设置。</p>
<p>目前，所有浏览器都支持该功能(IE8+：IE8/9需要使用XDomainRequest对象来支持CORS）)，CORS也已经成为主流的跨域解决方案。</p>
<h5 id="1、前端设置："><a href="#1、前端设置：" class="headerlink" title="1、前端设置："></a>1、前端设置：</h5><p>1.）原生ajax</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">// 前端设置是否带cookie</span><br><span class="line">xhr.withCredentials = true;</span><br><span class="line"></span><br><span class="line">var xhr = new XMLHttpRequest(); // IE8/9需用window.XDomainRequest兼容</span><br><span class="line"></span><br><span class="line">// 前端设置是否带cookie</span><br><span class="line">xhr.withCredentials = true;</span><br><span class="line"></span><br><span class="line">xhr.open(&apos;post&apos;, &apos;http://www.domain2.com:8080/login&apos;, true);</span><br><span class="line">xhr.setRequestHeader(&apos;Content-Type&apos;, &apos;application/x-www-form-urlencoded&apos;);</span><br><span class="line">xhr.send(&apos;user=admin&apos;);</span><br><span class="line"></span><br><span class="line">xhr.onreadystatechange = function() &#123;</span><br><span class="line">    if (xhr.readyState == 4 &amp;&amp; xhr.status == 200) &#123;</span><br><span class="line">        alert(xhr.responseText);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>2）jQuery ajax</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">$.ajax(&#123;</span><br><span class="line">    ...</span><br><span class="line">   xhrFields: &#123;</span><br><span class="line">       withCredentials: true    // 前端设置是否带cookie</span><br><span class="line">   &#125;,</span><br><span class="line">   crossDomain: true,   // 会让请求头中包含跨域的额外信息，但不会含cookie</span><br><span class="line">    ...</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>3.）vue框架</p>
<p>在vue-resource封装的ajax组件中加入以下代码：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Vue.http.options.credentials = true</span><br></pre></td></tr></table></figure>
<h5 id="2、服务端设置"><a href="#2、服务端设置" class="headerlink" title="2、服务端设置"></a>2、服务端设置</h5><p>若后端设置成功，前端浏览器控制台则不会出现跨域报错信息，反之，说明没设成功。</p>
<p>nodejs后台示例</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">var http = require(&apos;http&apos;);</span><br><span class="line">var server = http.createServer();</span><br><span class="line">var qs = require(&apos;querystring&apos;);</span><br><span class="line"></span><br><span class="line">server.on(&apos;request&apos;, function(req, res) &#123;</span><br><span class="line">    var postData = &apos;&apos;;</span><br><span class="line"></span><br><span class="line">    // 数据块接收中</span><br><span class="line">    req.addListener(&apos;data&apos;, function(chunk) &#123;</span><br><span class="line">        postData += chunk;</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    // 数据接收完毕</span><br><span class="line">    req.addListener(&apos;end&apos;, function() &#123;</span><br><span class="line">        postData = qs.parse(postData);</span><br><span class="line"></span><br><span class="line">        // 跨域后台设置</span><br><span class="line">        res.writeHead(200, &#123;</span><br><span class="line">            &apos;Access-Control-Allow-Credentials&apos;: &apos;true&apos;,     // 后端允许发送Cookie</span><br><span class="line">            &apos;Access-Control-Allow-Origin&apos;: &apos;http://www.domain1.com&apos;,    // 允许访问的域（协议+域名+端口）</span><br><span class="line">            /* </span><br><span class="line">             * 此处设置的cookie还是domain2的而非domain1，因为后端也不能跨域写cookie(nginx反向代理可以实现)，</span><br><span class="line">             * 但只要domain2中写入一次cookie认证，后面的跨域接口都能从domain2中获取cookie，从而实现所有的接口都能跨域访问</span><br><span class="line">             */</span><br><span class="line">            &apos;Set-Cookie&apos;: &apos;l=a123456;Path=/;Domain=www.domain2.com;HttpOnly&apos;  // HttpOnly的作用是让js无法读取cookie</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        res.write(JSON.stringify(postData));</span><br><span class="line">        res.end();</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">server.listen(&apos;8080&apos;);</span><br><span class="line">console.log(&apos;Server is running at port 8080...&apos;);</span><br></pre></td></tr></table></figure>
<h4 id="七、nginx代理跨域"><a href="#七、nginx代理跨域" class="headerlink" title="七、nginx代理跨域"></a>七、nginx代理跨域</h4><h5 id="1、-nginx配置解决iconfont跨域"><a href="#1、-nginx配置解决iconfont跨域" class="headerlink" title="1、 nginx配置解决iconfont跨域"></a>1、 nginx配置解决iconfont跨域</h5><p>浏览器跨域访问js、css、img等常规静态资源被同源策略许可，但iconfont字体文件(eot|otf|ttf|woff|svg)例外，此时可在nginx的静态资源服务器中加入以下配置。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">location / &#123;</span><br><span class="line">  add_header Access-Control-Allow-Origin *;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="1、nginx反向代理接口跨域"><a href="#1、nginx反向代理接口跨域" class="headerlink" title="1、nginx反向代理接口跨域"></a>1、nginx反向代理接口跨域</h5><p>跨域原理： 同源策略是浏览器的安全策略，不是HTTP协议的一部分。服务器端调用HTTP接口只是使用HTTP协议，不会执行JS脚本，不需要同源策略，也就不存在跨越问题。</p>
<p>实现思路：通过nginx配置一个代理服务器（域名与domain1相同，端口不同）做跳板机，反向代理访问domain2接口，并且可以顺便修改cookie中domain信息，方便当前域cookie写入，实现跨域登录。</p>
<p>nginx具体配置：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">#proxy服务器</span><br><span class="line">server &#123;</span><br><span class="line">    listen       81;</span><br><span class="line">    server_name  www.domain1.com;</span><br><span class="line"></span><br><span class="line">    location / &#123;</span><br><span class="line">        proxy_pass   http://www.domain2.com:8080;  #反向代理</span><br><span class="line">        proxy_cookie_domain www.domain2.com www.domain1.com; #修改cookie里域名</span><br><span class="line">        index  index.html index.htm;</span><br><span class="line"></span><br><span class="line">        # 当用webpack-dev-server等中间件代理接口访问nignx时，此时无浏览器参与，故没有同源限制，下面的跨域配置可不启用</span><br><span class="line">        add_header Access-Control-Allow-Origin http://www.domain1.com;  #当前端只跨域不带cookie时，可为*</span><br><span class="line">        add_header Access-Control-Allow-Credentials true;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>前端代码示例：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">var xhr = new XMLHttpRequest();</span><br><span class="line"></span><br><span class="line">// 前端开关：浏览器是否读写cookie</span><br><span class="line">xhr.withCredentials = true;</span><br><span class="line"></span><br><span class="line">// 访问nginx中的代理服务器</span><br><span class="line">xhr.open(&apos;get&apos;, &apos;http://www.domain1.com:81/?user=admin&apos;, true);</span><br><span class="line">xhr.send();</span><br></pre></td></tr></table></figure>
<p>Nodejs后台示例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">var http = require(&apos;http&apos;);</span><br><span class="line">var server = http.createServer();</span><br><span class="line">var qs = require(&apos;querystring&apos;);</span><br><span class="line"></span><br><span class="line">server.on(&apos;request&apos;, function(req, res) &#123;</span><br><span class="line">    var params = qs.parse(req.url.substring(2));</span><br><span class="line"></span><br><span class="line">    // 向前台写cookie</span><br><span class="line">    res.writeHead(200, &#123;</span><br><span class="line">        &apos;Set-Cookie&apos;: &apos;l=a123456;Path=/;Domain=www.domain2.com;HttpOnly&apos;   // HttpOnly:脚本无法读取</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    res.write(JSON.stringify(params));</span><br><span class="line">    res.end();</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">server.listen(&apos;8080&apos;);</span><br><span class="line">console.log(&apos;Server is running at port 8080...&apos;);</span><br></pre></td></tr></table></figure></p>
<h4 id="八、nodejs中间件代理跨域"><a href="#八、nodejs中间件代理跨域" class="headerlink" title="八、nodejs中间件代理跨域"></a>八、nodejs中间件代理跨域</h4><p>node中间件实现跨域代理，原理大致与nginx相同，都是通过启一个代理服务器，实现数据的转发，也可以通过设置cookieDomainRewrite参数修改响应头中cookie中域名，实现当前域的cookie写入，方便接口登录认证。</p>
<h5 id="1、-非vue框架的跨域（2次跨域）"><a href="#1、-非vue框架的跨域（2次跨域）" class="headerlink" title="1、 非vue框架的跨域（2次跨域）"></a>1、 非vue框架的跨域（2次跨域）</h5><p>利用node + express + http-proxy-middleware搭建一个proxy服务器。</p>
<p>前端代码示例：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">var xhr = new XMLHttpRequest();</span><br><span class="line"></span><br><span class="line">// 前端开关：浏览器是否读写cookie</span><br><span class="line">xhr.withCredentials = true;</span><br><span class="line"></span><br><span class="line">// 访问http-proxy-middleware代理服务器</span><br><span class="line">xhr.open(&apos;get&apos;, &apos;http://www.domain1.com:3000/login?user=admin&apos;, true);</span><br><span class="line">xhr.send();</span><br></pre></td></tr></table></figure>
<p>中间件服务器</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">var express = require(&apos;express&apos;);</span><br><span class="line">var proxy = require(&apos;http-proxy-middleware&apos;);</span><br><span class="line">var app = express();</span><br><span class="line"></span><br><span class="line">app.use(&apos;/&apos;, proxy(&#123;</span><br><span class="line">    // 代理跨域目标接口</span><br><span class="line">    target: &apos;http://www.domain2.com:8080&apos;,</span><br><span class="line">    changeOrigin: true,</span><br><span class="line"></span><br><span class="line">    // 修改响应头信息，实现跨域并允许带cookie</span><br><span class="line">    onProxyRes: function(proxyRes, req, res) &#123;</span><br><span class="line">        res.header(&apos;Access-Control-Allow-Origin&apos;, &apos;http://www.domain1.com&apos;);</span><br><span class="line">        res.header(&apos;Access-Control-Allow-Credentials&apos;, &apos;true&apos;);</span><br><span class="line">    &#125;,</span><br><span class="line"></span><br><span class="line">    // 修改响应信息中的cookie域名</span><br><span class="line">    cookieDomainRewrite: &apos;www.domain1.com&apos;  // 可以为false，表示不修改</span><br><span class="line">&#125;));</span><br><span class="line"></span><br><span class="line">app.listen(3000);</span><br><span class="line">console.log(&apos;Proxy server is listen at port 3000...&apos;);</span><br></pre></td></tr></table></figure>
<p>Nodejs后台同（六：nginx）</p>
<h5 id="2、-vue框架的跨域（1次跨域）"><a href="#2、-vue框架的跨域（1次跨域）" class="headerlink" title="2、 vue框架的跨域（1次跨域）"></a>2、 vue框架的跨域（1次跨域）</h5><p>利用node + webpack + webpack-dev-server代理接口跨域。在开发环境下，由于vue渲染服务和接口代理服务都是webpack-dev-server同一个，所以页面与代理接口之间不再跨域，无须设置headers跨域信息了。</p>
<p>webpack.config.js部分配置：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">module.exports = &#123;</span><br><span class="line">    entry: &#123;&#125;,</span><br><span class="line">    module: &#123;&#125;,</span><br><span class="line">    ...</span><br><span class="line">    devServer: &#123;</span><br><span class="line">        historyApiFallback: true,</span><br><span class="line">        proxy: [&#123;</span><br><span class="line">            context: &apos;/login&apos;,</span><br><span class="line">            target: &apos;http://www.domain2.com:8080&apos;,  // 代理跨域目标接口</span><br><span class="line">            changeOrigin: true,</span><br><span class="line">            secure: false,  // 当代理某些https服务报错时用</span><br><span class="line">            cookieDomainRewrite: &apos;www.domain1.com&apos;  // 可以为false，表示不修改</span><br><span class="line">        &#125;],</span><br><span class="line">        noInfo: true</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="九、WebSocket协议跨域"><a href="#九、WebSocket协议跨域" class="headerlink" title="九、WebSocket协议跨域"></a>九、WebSocket协议跨域</h4><p>WebSocket protocol是HTML5一种新的协议。它实现了浏览器与服务器全双工通信，同时允许跨域通讯，是server push技术的一种很好的实现。</p>
<p>原生WebSocket API使用起来不太方便，我们使用Socket.io，它很好地封装了webSocket接口，提供了更简单、灵活的接口，也对不支持webSocket的浏览器提供了向下兼容。</p>
<p>前端代码：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">&lt;div&gt;user input：&lt;input type=&quot;text&quot;&gt;&lt;/div&gt;</span><br><span class="line">&lt;script src=&quot;./socket.io.js&quot;&gt;&lt;/script&gt;</span><br><span class="line">&lt;script&gt;</span><br><span class="line">var socket = io(&apos;http://www.domain2.com:8080&apos;);</span><br><span class="line"></span><br><span class="line">// 连接成功处理</span><br><span class="line">socket.on(&apos;connect&apos;, function() &#123;</span><br><span class="line">    // 监听服务端消息</span><br><span class="line">    socket.on(&apos;message&apos;, function(msg) &#123;</span><br><span class="line">        console.log(&apos;data from server: ---&gt; &apos; + msg); </span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    // 监听服务端关闭</span><br><span class="line">    socket.on(&apos;disconnect&apos;, function() &#123; </span><br><span class="line">        console.log(&apos;Server socket has closed.&apos;); </span><br><span class="line">    &#125;);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">document.getElementsByTagName(&apos;input&apos;)[0].onblur = function() &#123;</span><br><span class="line">    socket.send(this.value);</span><br><span class="line">&#125;;</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure>
<p>Nodejs socket后台</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">var http = require(&apos;http&apos;);</span><br><span class="line">var socket = require(&apos;socket.io&apos;);</span><br><span class="line"></span><br><span class="line">// 启http服务</span><br><span class="line">var server = http.createServer(function(req, res) &#123;</span><br><span class="line">    res.writeHead(200, &#123;</span><br><span class="line">        &apos;Content-type&apos;: &apos;text/html&apos;</span><br><span class="line">    &#125;);</span><br><span class="line">    res.end();</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">server.listen(&apos;8080&apos;);</span><br><span class="line">console.log(&apos;Server is running at port 8080...&apos;);</span><br><span class="line"></span><br><span class="line">// 监听socket连接</span><br><span class="line">socket.listen(server).on(&apos;connection&apos;, function(client) &#123;</span><br><span class="line">    // 接收信息</span><br><span class="line">    client.on(&apos;message&apos;, function(msg) &#123;</span><br><span class="line">        client.send(&apos;hello：&apos; + msg);</span><br><span class="line">        console.log(&apos;data from client: ---&gt; &apos; + msg);</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line">    // 断开处理</span><br><span class="line">    client.on(&apos;disconnect&apos;, function() &#123;</span><br><span class="line">        console.log(&apos;Client socket has closed.&apos;); </span><br><span class="line">    &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>参考资料：</p>
<p><a href="https://segmentfault.com/a/1190000011145364" target="_blank" rel="noopener">前端常见跨域解决方案（全）</a></p>
      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center">
  <div>Donate comment here</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="Tony 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Tony 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/04/12/vue父子组件数据传递/" rel="next" title="vue父子组件数据传递">
                <i class="fa fa-chevron-left"></i> vue父子组件数据传递
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/05/08/vue双向数据绑定/" rel="prev" title="vue双向数据绑定">
                vue双向数据绑定 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Tony</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">65</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#什么是跨域？"><span class="nav-number">1.</span> <span class="nav-text">什么是跨域？</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#广义的跨域："><span class="nav-number">1.1.</span> <span class="nav-text">广义的跨域：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#什么是同源策略？"><span class="nav-number">1.2.</span> <span class="nav-text">什么是同源策略？</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#常见跨域场景"><span class="nav-number">1.3.</span> <span class="nav-text">常见跨域场景</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#跨域解决方案"><span class="nav-number">1.4.</span> <span class="nav-text">跨域解决方案</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#一、通过jsonp跨域"><span class="nav-number">1.5.</span> <span class="nav-text">一、通过jsonp跨域</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#二、document-domain-iframe跨域"><span class="nav-number">1.6.</span> <span class="nav-text">二、document.domain+iframe跨域</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#三、location-hash-iframe跨域"><span class="nav-number">1.7.</span> <span class="nav-text">三、location.hash+iframe跨域</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#四、window-name-iframe跨域"><span class="nav-number">1.8.</span> <span class="nav-text">四、window.name + iframe跨域</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#五、postMessage跨域"><span class="nav-number">1.9.</span> <span class="nav-text">五、postMessage跨域</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#六、跨域资源共享（CORS）"><span class="nav-number">1.10.</span> <span class="nav-text">六、跨域资源共享（CORS）</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#1、前端设置："><span class="nav-number">1.10.1.</span> <span class="nav-text">1、前端设置：</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2、服务端设置"><span class="nav-number">1.10.2.</span> <span class="nav-text">2、服务端设置</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#七、nginx代理跨域"><span class="nav-number">1.11.</span> <span class="nav-text">七、nginx代理跨域</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#1、-nginx配置解决iconfont跨域"><span class="nav-number">1.11.1.</span> <span class="nav-text">1、 nginx配置解决iconfont跨域</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#1、nginx反向代理接口跨域"><span class="nav-number">1.11.2.</span> <span class="nav-text">1、nginx反向代理接口跨域</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#八、nodejs中间件代理跨域"><span class="nav-number">1.12.</span> <span class="nav-text">八、nodejs中间件代理跨域</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#1、-非vue框架的跨域（2次跨域）"><span class="nav-number">1.12.1.</span> <span class="nav-text">1、 非vue框架的跨域（2次跨域）</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2、-vue框架的跨域（1次跨域）"><span class="nav-number">1.12.2.</span> <span class="nav-text">2、 vue框架的跨域（1次跨域）</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#九、WebSocket协议跨域"><span class="nav-number">1.13.</span> <span class="nav-text">九、WebSocket协议跨域</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tony</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  



  
  









  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>